//
// Created by mio on 25-4-22.
//

#ifndef RTMPSESSION_H
#define RTMPSESSION_H

#include <memory>
#include <mutex>
#include <RtmpConnection.h>

#include "amf.h"

class RtmpSink;
class RtmpConnection;
class RtmpSession
{
public:
    RtmpSession();
    virtual ~RtmpSession();

    void SetAvcSequenceHeader(std::shared_ptr<char> avc_sequence_header, uint32_t avc_sequence_header_size)
    {
        std::lock_guard<std::mutex> lock(mtx_);
        avc_sequence_header_ = avc_sequence_header;
        avc_sequence_header_size_ = avc_sequence_header_size;
    }

    void SetAacSequenceHeader(std::shared_ptr<char> aac_sequence_header, uint32_t aac_sequence_header_size)
    {
        std::lock_guard<std::mutex> lock(mtx_);
        aac_sequence_header_ = aac_sequence_header;
        aac_sequence_header_size_ = aac_sequence_header_size;
    }

    // session 添加客户端
    void AddSink(std::shared_ptr<RtmpSink> sink);
    // 移除客户端
    void RemoveSink(std::shared_ptr<RtmpSink> sink);
    // 获取当前有多少人在直播间，包括主播和观众
    int GetClients();
    // 发送消息通知, 通知元数据
    void SendMetaData(AmfObjects& metaData);
    // 发送数据
    void SendMediaData(uint8_t type, uint64_t timestamp, std::shared_ptr<char> data, uint32_t size);
    // 获取推流对象
    std::shared_ptr<RtmpConnection> GetPublisher();


private:
    std::mutex mtx_;
    bool has_publisher_ = false;
    std::weak_ptr<RtmpSink> publisher_;
    std::unordered_map<int, std::weak_ptr<RtmpSink>> rtmp_sinks_; // 管理客户端的接入和移出

    std::shared_ptr<char> avc_sequence_header_;
    std::shared_ptr<char> aac_sequence_header_;
    uint32_t avc_sequence_header_size_ = 0;
    uint32_t aac_sequence_header_size_ = 0;
};

using RtmpSessionPtr = std::shared_ptr<RtmpSession>;

#endif //RTMPSESSION_H
